<template>
  <a-modal
    :open="visible"
    :title="title"
    width="800px"
    @ok="handleOk"
    @cancel="handleCancel"
    :confirmLoading="loading"
  >
    <a-form
      :model="form"
      :rules="rules"
      ref="formRef"
      layout="vertical"
    >
      <a-form-item label="公告标题" name="title">
        <a-input v-model:value="form.title" placeholder="请输入公告标题" />
      </a-form-item>
      
      <a-form-item label="公告内容" name="content">
        <a-textarea
          v-model:value="form.content"
          :rows="6"
          placeholder="请输入公告内容"
        />
      </a-form-item>
      
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="公告类型" name="type">
            <a-select v-model:value="form.type" placeholder="请选择公告类型">
              <a-select-option :value="0">普通公告</a-select-option>
              <a-select-option :value="1">紧急公告</a-select-option>
              <a-select-option :value="2">维护公告</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        
        <a-col :span="12">
          <a-form-item label="是否置顶" name="isTop">
            <a-select v-model:value="form.isTop" placeholder="请选择是否置顶">
              <a-select-option :value="0">否</a-select-option>
              <a-select-option :value="1">是</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      
      <a-form-item label="过期时间" name="expireTime">
        <a-date-picker
          v-model:value="form.expireTime"
          show-time
          placeholder="请选择过期时间（可选）"
          style="width: 100%"
        />
      </a-form-item>
      
      <a-form-item v-if="mode === 'edit'" label="状态" name="status">
        <a-select v-model:value="form.status" placeholder="请选择状态">
          <a-select-option :value="0">下线</a-select-option>
          <a-select-option :value="1">正常</a-select-option>
        </a-select>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, reactive, watch, computed } from 'vue'
import { message } from 'ant-design-vue'
import { addAnnouncement, updateAnnouncement, type AnnouncementAddRequest, type AnnouncementEditRequest } from '@/api/announcementController'
import dayjs from 'dayjs'

interface Props {
  visible: boolean
  mode: 'add' | 'edit'
  initialData?: any
}

interface Emits {
  (e: 'update:visible', visible: boolean): void
  (e: 'success'): void
}

const props = withDefaults(defineProps<Props>(), {
  mode: 'add'
})

const emit = defineEmits<Emits>()

const formRef = ref()
const loading = ref(false)

const form = reactive({
  id: undefined as string | undefined,
  title: '',
  content: '',
  type: 0,
  isTop: 0,
  status: 1,
  expireTime: undefined as any
})

const rules = {
  title: [
    { required: true, message: '请输入公告标题', trigger: 'blur' },
    { max: 512, message: '标题长度不能超过512个字符', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入公告内容', trigger: 'blur' },
    { max: 10000, message: '内容长度不能超过10000个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择公告类型', trigger: 'change' }
  ],
  isTop: [
    { required: true, message: '请选择是否置顶', trigger: 'change' }
  ]
}

const title = computed(() => {
  return props.mode === 'add' ? '创建公告' : '编辑公告'
})

// 监听初始数据变化
watch(() => props.initialData, (newData) => {
  if (newData && props.mode === 'edit') {
    form.id = newData.id
    form.title = newData.title || ''
    form.content = newData.content || ''
    form.type = newData.type ?? 0
    form.isTop = newData.isTop ?? 0
    form.status = newData.status ?? 1
    form.expireTime = newData.expireTime ? dayjs(newData.expireTime) : undefined
  }
}, { immediate: true })

// 监听弹窗显示状态
watch(() => props.visible, (visible) => {
  if (!visible) {
    resetForm()
  }
})

const resetForm = () => {
  formRef.value?.resetFields()
  Object.assign(form, {
    id: undefined,
    title: '',
    content: '',
    type: 0,
    isTop: 0,
    status: 1,
    expireTime: undefined
  })
}

const handleOk = async () => {
  try {
    await formRef.value.validate()
    loading.value = true

    const formData = {
      ...form,
      expireTime: form.expireTime ? form.expireTime.format('YYYY-MM-DD HH:mm:ss') : undefined
    }

    if (props.mode === 'add') {
      await addAnnouncement(formData as AnnouncementAddRequest)
      message.success('创建公告成功')
    } else {
      await updateAnnouncement(formData as AnnouncementEditRequest)
      message.success('更新公告成功')
    }

    emit('success')
    emit('update:visible', false)
  } catch (error) {
    console.error('操作失败:', error)
  } finally {
    loading.value = false
  }
}

const handleCancel = () => {
  emit('update:visible', false)
}
</script>

<style scoped>
.ant-form-item {
  margin-bottom: 16px;
}

/* 黑暗模式适配 */
[data-theme="dark"] .ant-modal-content {
  background: #1f1f1f !important;
  color: #ffffff;
}

[data-theme="dark"] .ant-modal-header {
  background: #262626 !important;
  border-bottom-color: #404040 !important;
}

[data-theme="dark"] .ant-modal-title {
  color: #ffffff !important;
}

[data-theme="dark"] .ant-modal-body {
  background: #1f1f1f !important;
  color: #ffffff;
}

[data-theme="dark"] .ant-modal-footer {
  background: #262626 !important;
  border-top-color: #404040 !important;
}

[data-theme="dark"] .ant-form-item-label > label {
  color: #ffffff !important;
}

[data-theme="dark"] .ant-input,
[data-theme="dark"] .ant-input-number,
[data-theme="dark"] .ant-select-selector,
[data-theme="dark"] .ant-picker,
[data-theme="dark"] .ant-input.ant-input-textarea {
  background: #262626 !important;
  border-color: #404040 !important;
  color: #ffffff !important;
}

[data-theme="dark"] .ant-input:focus,
[data-theme="dark"] .ant-input-number:focus,
[data-theme="dark"] .ant-select-focused .ant-select-selector,
[data-theme="dark"] .ant-picker:focus {
  border-color: #1890ff !important;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2) !important;
}

[data-theme="dark"] .ant-select-arrow,
[data-theme="dark"] .ant-picker-suffix {
  color: #ffffff !important;
}
</style>
